<?php

namespace app\services;

use app\payment\PayFactory;
use app\traits\Page;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserBankCard;
use plugin\admin\app\model\UserPropertyLog;
use plugin\admin\app\model\UserWithdraw;
use support\Db;

class WithdrawService
{
    public static function list($page, $length, $status = UserWithdraw::STATUS_WAITING_AUDIT)
    {
        $offset = ($page - 1) * $length;
        $query = Db::table('wa_user_withdraws', 'uw')
            ->select(['uw.id', 'ubc.number', 'uw.amount', 'uw.created_time', 'uw.reject_reason', 'uw.status', 'ubc.bank_name'])
            ->join(Db::raw('wa_user_bank_cards as ubc'), 'ubc.id', '=', 'uw.card_id', 'left')
            ->where('uw.user_id', get_user_id())
            ->where('uw.status', $status);

        $count = (clone $query)->count();
        $list = $query->offset($offset)->limit($length)->orderByDesc('id')->get()->toArray();

        foreach ($list as $key=>$item) {
            $item = json_decode(json_encode($item), true);
            $list[$key] = $item;
            $list[$key]['status_text'] = UserWithdraw::getStatusText($item['status']);
            $list[$key]['number'] = substr($item['number'], strlen($item['number']) - 4);
        }

        return Page::wrap($count, $page, $length, $list);
    }

    public static function add($data)
    {
        if (!UserBankCard::where('user_id', get_user_id())->where('id', $data['card_id'])->count()) {
            throw new \Exception('卡不存在');
        }

        $config = ConfigService::getByGroup('withdraw');

        if ($data['amount'] <= 0) {
            throw new \Exception('不正确的提现金额');
        }

        if ($config['min_withdraw_amount'] > $data['amount']) {
            throw new \Exception('最小提现额度为' . $config['min_withdraw_amount']);
        }

        $fee = bcmul($config['withdraw_fee']/100, $data['amount'], 2);

        $withdrawId = UserWithdraw::insertGetId([
            'user_id' => get_user_id(),
            'card_id' => $data['card_id'],
            'amount' => $data['amount'],
            'fee' => $fee,
            'created_time' => date('Y-m-d H:i:s'),
            'status' => UserWithdraw::STATUS_WAITING_AUDIT,
        ]);

        PropertyService::reduce(get_user_id(), PayFactory::BALANCE, $data['amount'], UserPropertyLog::WITHDRAW, '', $withdrawId);

    }

    public static function totalWithdrawAmount()
    {
        return UserWithdraw::where('status', UserWithdraw::STATUS_AGREE)->sum('amount');
    }

    public static function withdrawAmountSta($startTime, $endTime)
    {
        return UserWithdraw::where('status', UserWithdraw::STATUS_AGREE)->whereBetween('created_time', [$startTime, $endTime])->sum('amount');
    }
}